<template>
	<view>
		<view border-bottom class="line u-p-l-40 u-p-r-40">
			<u-form :model="form" ref="uForm" class="form">
				<u-form-item label="用户名" prop="name" required>
					<u-input v-model="form.name" placeholder="请输入用户名" class="form-item"/>
				</u-form-item>
				<u-form-item label="邮箱" prop="email" required>
					<u-input v-model="form.email" placeholder="请输入邮箱" class="form-item"/>
				</u-form-item>
				<u-form-item label="密码" prop="password" required>
					<u-input v-model="form.password" placeholder="请输入密码" type="password" class="form-item"/>
				</u-form-item>
				<u-form-item label="确认密码" prop="password_confirmation" required>
					<u-input v-model="form.password_confirmation" placeholder="请确认密码" type="password" class="form-item"/>
				</u-form-item>
			</u-form>
			<u-button @click="submit">提交</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
						name: '',
						email: '',
						password:'',
						password_confirmation:''
					},
				rules: {
						name: [
							{ 
								required: true, 
								message: '请输入账号', 
								// 可以单个或者同时写两个触发验证方式 
								trigger: ['change','blur'],
							}
						],
						email: [
							{
								 type:'email',
								message: '请输入邮箱', 
								trigger: 'blur'
							}
						],
						password: [
							{
								min: 5,
								message: '密码要5个数字',
								trigger: 'change'
							}
						],
						password_confirmation: [{
								required: true,
								message: "确认密码不能为空",
								trigger: "blur"
							},
							{
								trigger: 'blur',
								validator: (rule, value, callback) => {
									if (value !== this.form.password) {
										callback(new Error('两次输入密码不一致'))
									} else {
										callback()
									}
								}
							}
						],
						}		
			}
		},
		methods: {
			/**
			 * 执行注册
			 */
			submit(){
				// 1.表单验证
				this.$refs.uForm.validate(async valid => {
						if (valid) {
							console.log('验证通过');
							//发起注册网络请求
							await this.$u.api.authRegister(this.form)
							this.$u.toast('注册成功，将自动跳转到登录页')
							// 注册成功之后，重定向到登录页面(redirect)
							setTimeout(() => {
								uni.redirectTo({
									url:'/pages/auth/login'
								})
							},1500)
								
						} else {
							this.$u.toast('注册失败')
						}
					});
						
				// 2.准备提交参数的表单
				// const params = {
				// 	name:this.name,
				// 	email:this.email,
				// 	password:this.password,
				// 	password_confirmation:this.password_confirmation
				// }
				// 3.请求API,执行注册
				// const res = await this.$u.api.authRegister(params)
				
				// 4.注册成功之后,重定向到登录(redirect)
				
				
			}
			
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	}
</script>


<style lang="scss" scoped>
	.line {
		width: 100%;
		height: 20rpx;
		background-color: #DDDDDD;
	}
 
	.form {
		width: 95%;
		margin: auto;
 
		.form-item {
			margin-left: 50rpx;
		}
	}
</style>
